<template>
  <t-card>
    <t-row justify="start" class="controller-header">
      <t-col flex="auto">
        <h3>消息列表</h3>
      </t-col>
    </t-row>

    <t-table
      :data="messageList"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      @page-change="onPageChange"
    >
      <template #status="{ row }">
        <t-tag v-if="!row.isRead" theme="danger" variant="light">未读</t-tag>
        <t-tag v-else theme="success" variant="light">已读</t-tag>
      </template>

      <template #createTime="{ row }">
        {{ formatTime(row.createTime) }}
      </template>

      <template #operation="{ row }">
        <t-space>
          <t-link theme="primary" hover="color" @click="showDetail(row)">查看详情</t-link>
          <t-link v-if="!row.isRead" theme="primary" hover="color" @click="handleMarkAsRead(row)">标记已读</t-link>
        </t-space>
      </template>
    </t-table>

    <!-- 消息详情弹窗 -->
    <t-dialog v-model:visible="dialogVisible" :header="currentMessage?.title" :footer="false" width="500px">
      <template #body>
        <div class="message-detail">
          <div class="message-content">
            <p>{{ currentMessage?.content }}</p>
          </div>
          <div class="message-info">
            <p class="time">时间：{{ formatTime(currentMessage?.createTime) }}</p>
            <p class="status">
              状态：
              <t-tag v-if="currentMessage && !currentMessage.isRead" theme="danger" variant="light">未读</t-tag>
              <t-tag v-else theme="success" variant="light">已读</t-tag>
            </p>
          </div>
          <div v-if="currentMessage?.businessId" class="message-actions">
            <t-button @click="handleView(currentMessage)">前往处理</t-button>
          </div>
        </div>
      </template>
    </t-dialog>
  </t-card>
</template>

<script setup lang="ts">
import { MessagePlugin } from 'tdesign-vue-next';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { getMessagesApi, markAsReadApi } from '@/api/message';
import { formatTime } from '@/utils/format';

const router = useRouter();
const loading = ref(false);
const messageList = ref([]);
const dialogVisible = ref(false);
const currentMessage = ref(null);

const columns = [
  { colKey: 'title', title: '标题', width: 200 },
  { colKey: 'content', title: '内容', width: 300 },
  { colKey: 'status', title: '状态', width: 100 },
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'operation', title: '操作', width: 160 },
];

const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
});

// 显示消息详情
const showDetail = (row: any) => {
  currentMessage.value = row;
  dialogVisible.value = true;
  if (!row.isRead) {
    handleMarkAsRead(row);
  }
};

// 加载消息列表
const loadMessages = async () => {
  loading.value = true;
  try {
    const response = await getMessagesApi({
      pageNo: pagination.value.current,
      pageSize: pagination.value.pageSize,
    });
    messageList.value = response.records;
    pagination.value.total = response.total;
  } catch (error) {
    console.error('加载消息失败:', error);
  } finally {
    loading.value = false;
  }
};

// 处理页码变化
const onPageChange = (page: any) => {
  pagination.value = page;
  loadMessages();
};

// 查看详情
const handleView = (row: any) => {
  dialogVisible.value = false;
  switch (row.type) {
    case 'order':
      router.push(`/afterSales/order/index`);
      break;
    case 'after_sales':
      router.push(`/afterSales/feedback/index`);
      break;
    default:
      break;
  }
};

// 标记已读
const handleMarkAsRead = async (row: any) => {
  try {
    await markAsReadApi(row.id);
    MessagePlugin.success('标记消息已读成功');
    loadMessages();
  } catch (error) {
    console.error('标记消息已读失败:', error);
  }
};

onMounted(() => {
  loadMessages();
});
</script>

<style lang="less" scoped>
.controller-header {
  margin-bottom: 24px;

  h3 {
    margin: 0;
    font-size: 20px;
  }
}

.message-detail {
  padding: 16px;

  .message-content {
    margin-bottom: 24px;
    font-size: 14px;
    line-height: 1.6;
    color: var(--td-text-color-primary);
  }

  .message-info {
    margin-bottom: 24px;
    font-size: 13px;
    color: var(--td-text-color-secondary);

    .time,
    .status {
      margin-bottom: 8px;
    }
  }

  .message-actions {
    text-align: right;
  }
}
</style>
